
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

global.rosterList = null;

// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
// app.get('/settings', routes.settings);
// app.get('/users', user.list);

io.sockets.on('connection', function (socket) {
  socket.on('do_emit', function (data) {
  	var returnData = {};

  	switch(data.event){
  		case 'select': 
  			returnData.event = 'single_update';
  			returnData.data = { id: data.id };

  			var list2 = global.rosterList;
  			for (var i=0; i<list2.length; i++) {
  				if(list2[i].id==data.id){
  					list2[i].status="active";
  				}
  				else{
  					if(list2[i].status && list2[i].status == "active")
  						list2[i].status = "done";
  				}
  			}

  			global.rosterList = list2 //update roster list here
  			break;
  		case 'reset':
  			var list = data.list;
		  	for(var i=0; i<list.length; i++){
		  		list[i].status = "default";
		  	}
  			returnData.event = 'full_refresh';
  			returnData.data = list;

  			global.rosterList = list;

  			break;
  		case 'save':
  			var saveList = global.rosterList;
  			for(var i=0; i<saveList.length; i++){
		  		for(var i2=0; i<data.list.length; i2++){
		  			if(saveList[i].id == data.list[i2].id){
		  				saveList[i].isPresent = data.list[i2].isPresent;
		  				break;
		  			}
		  		}
		  	}
  			returnData.event = 'refresh_present';
  			returnData.data = saveList;

  			global.rosterList = saveList;

  			break;
  	}

    socket.broadcast.emit('update', returnData);
  });
});

// var chat = io
//   .of('/reset')
//   .on('connection', function (socket) {
//   	socket.on('reset', function (data) {
// 	  	var list = data.list;
// 	  	for(var i=0; i<list.length; i++){
// 	  		list[i].status = "default";
// 	  	}

// 	  	socket.broadcast.emit('full_refresh', { data: list });
// 	  });
//   });

server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
